var express = require('express');
var router = express.Router();
var dbcomm = require('../util/dbcomm');
var db = require('../util/db');
var moment = require('moment');
var now = moment().format('YYYY年MM月DD日') ;//日期
var bodyParser = require('body-parser');
var multer  = require('multer');//用express的第三方中间件 multer 实现文件上传功能。
var fs = require('fs')
var upload = multer({dest:'./templates/BackStage/image'});

//处理页面数据 
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());



router.get('/showStaffresourceinformation',function(req,res){
	var dates = req.query;
	var pagesum;
	dbcomm.query("select * from sys_staffresourceinformation where staffState = 0",function(err,data){
		if(err) {throw err;}else{
			pagesum = data.length;
			var sql = "select * from sys_staffresourceinformation where staffState = 0 limit "+(dates.pageNum-1)*5+",5";
			dbcomm.query(sql,function(err,data){
				if(err) {throw err;}else{
					data[data.length] = {listlength:pagesum};
					res.send(data);
				}
			});
		}
	});
})
router.get('/finddepart',function(req,res){
	dbcomm.query("select departmentNo no,departmentName name from sys_departmentinformation",function(err,data){
		if(err) {throw err;}else{
            res.send(data);
		}
	});
})

router.get('/findrole',function(req,res){
	dbcomm.query("select roleNo no,roleName name from sys_roleinformation",function(err,data){
		if(err) {throw err;}else{
            res.send(data);
		}
	});
})

router.get('/deletestaffresourceinformation',function(req,res){
	var datas = req.query;
	var sql = "UPDATE sys_staffresourceinformation SET staffState =2 WHERE staffNo ="+datas.staffNo;
	console.log(sql);
	dbcomm.query(sql,function(err,data){
		if(err) {throw err;}else{
            res.send(data);
		}
	});
})
router.get('/addstaffresourceinformation',function(req,res){
    var datas = req.query;
	var sql = "INSERT INTO `sys_staffresourceinformation` "+
	"(`staffName`, `staffBir`, `staffTel`, `staffLoc`, `staffUrgTel`, `staffPay`, `staffComment`, `departNo`,isManager, `staffRole`) "+
	"VALUES ('"+datas.staffname+"', '"+datas.staffBir+"', '"+datas.staffTel+"', '"+datas.staffLoc+"', '"+datas.staffUrgTel+"', "+datas.staffPay+", '"+datas.staffComment+"', "+datas.departNo+","+datas.isManager+", "+datas.roleNo+");"
	dbcomm.query(sql,function(err,data){
		if(err) {throw err;}else{
            res.redirect("/BackStage/moduols");
		}
	});
})

router.get('/updatestaffresourceinformation',function(req,res){
    var datas = req.query;
	console.log(datas);
	var sql = "UPDATE sys_staffresourceinformation SET "+
	" staffName='"+datas.staffname+"',staffSex='"+datas.staffSex+"',staffBir='"+datas.staffBir+"',staffTel='"+datas.staffTel+"',"+
	"staffLoc='"+datas.staffLoc+"',staffUrgTel='"+datas.staffUrgTel+"',staffPay="+datas.staffPay+","+
	"staffComment='"+datas.staffComment+"',departNo="+datas.departNo+",isManager="+datas.isManager+",staffRole="+datas.roleNo+" WHERE staffNo ="+datas.staffNo;
	dbcomm.query(sql,function(err,data){
		if(err) {throw err;}else{
            res.redirect("/BackStage/moduols");
		}
	});
})



router.post('/selectStaff',function(req,res){
    var para = req.body;
    var sql = '';
    sql = "SELECT * FROM sys_staffresourceinformation ";
    db.page(sql,para,function(data){
        res.send(data);
    });
});

router.post('/deleteStaff',function(req,res){
    var para = req.body;
    var sql='';
    sql ="delete from sys_staffresourceinformation where "+para.primaryKey+" = '"+para.primaryKeyName+"'";
    db.delete(sql,para,function(data){
        res.send(data);
    });
});

router.post('/insertStaff',upload.array('IMAGE',9),function(req,res){
    var para = req.body;
    var arr = req.query;
    var file=req.files;
    if(file){
        file.forEach(function(items,i){
            console.log("name["+i+"]:"+arr.fileName[i]);
            name=items.originalname;
            nameArray=name.split('');
            var nameMime=[];
            l=nameArray.pop();
            nameMime.unshift(l);
            while(nameArray.length!=0&&l!='.'){
                l=nameArray.pop();
                nameMime.unshift(l);
            }
            Mime=nameMime.join('');
            fs.renameSync('./templates/BackStage/image/'+items.filename,'./templates/BackStage/image/'+items.filename+Mime);
            para[arr.fileName[i]] = '/BackStage/image/'+items.filename+Mime;
            console.log(arr.fileName[i])
        })
    }
    var sql='';
    sql ="INSERT INTO sys_staffresourceinformation";
    db.insert(sql,para,function(data){
        if(data.result == 'succeed'){
            res.redirect(para.returnUrl);
        }
    });
});

router.post('/updateStaff',upload.array('IMAGE',9),function(req,res){
    var para = req.body;
    console.log(para);
    var arr = req.query;
    var file=req.files;
    if(file){
        file.forEach(function(items,i){
            console.log("name["+i+"]:"+arr.fileName[i]);
            name=items.originalname;
            nameArray=name.split('');
            var nameMime=[];
            l=nameArray.pop();
            nameMime.unshift(l);
            while(nameArray.length!=0&&l!='.'){
                l=nameArray.pop();
                nameMime.unshift(l);
            }
            Mime=nameMime.join('');
            fs.renameSync('./templates/BackStage/image/'+items.filename,'./templates/BackStage/image/'+items.filename+Mime);
            para[arr.fileName[i]] = '/BackStage/image/'+items.filename+Mime;
        })
    }
    var sql='';
    sql ="update sys_staffresourceinformation SET ";
    db.update(sql,para,function(data){
        if(data.result == 'succeed'){
            res.redirect(para.returnUrl);
        }
    });
});


router.post('/selectDepart',function(req,res){
    var para = req.body;
    var sql = '';
    sql = "SELECT * FROM sys_departmentinformation ";
    db.page(sql,para,function(data){
        res.send(data);
    });
});

router.post('/deleteDepart',function(req,res){
    var para = req.body;
    var sql='';
    sql ="delete from sys_departmentinformation where "+para.primaryKey+" = '"+para.primaryKeyName+"'";
    db.delete(sql,para,function(data){
        res.send(data);
    });
});

router.post('/insertDepart',upload.array('IMAGE',9),function(req,res){
    var para = req.body;
    var arr = req.query;
    var file=req.files;
    if(file){
        file.forEach(function(items,i){
            console.log("name["+i+"]:"+arr.fileName[i]);
            name=items.originalname;
            nameArray=name.split('');
            var nameMime=[];
            l=nameArray.pop();
            nameMime.unshift(l);
            while(nameArray.length!=0&&l!='.'){
                l=nameArray.pop();
                nameMime.unshift(l);
            }
            Mime=nameMime.join('');
            fs.renameSync('./templates/BackStage/image/'+items.filename,'./templates/BackStage/image/'+items.filename+Mime);
            para[arr.fileName[i]] = '/BackStage/image/'+items.filename+Mime;
            console.log(arr.fileName[i])
        })
    }
    var sql='';
    sql ="INSERT INTO sys_drink";
    db.insert(sql,para,function(data){
        if(data.result == 'succeed'){
            res.redirect(para.returnUrl);
        }
    });
});

router.post('/updateDepart',upload.array('IMAGE',9),function(req,res){
    var para = req.body;
    console.log(para);
    var arr = req.query;
    var file=req.files;
    if(file){
        file.forEach(function(items,i){
            console.log("name["+i+"]:"+arr.fileName[i]);
            name=items.originalname;
            nameArray=name.split('');
            var nameMime=[];
            l=nameArray.pop();
            nameMime.unshift(l);
            while(nameArray.length!=0&&l!='.'){
                l=nameArray.pop();
                nameMime.unshift(l);
            }
            Mime=nameMime.join('');
            fs.renameSync('./templates/BackStage/image/'+items.filename,'./templates/BackStage/image/'+items.filename+Mime);
            para[arr.fileName[i]] = '/BackStage/image/'+items.filename+Mime;
        })
    }
    var sql='';
    sql ="update sys_departmentinformation SET ";
    db.update(sql,para,function(data){
        if(data.result == 'succeed'){
            res.redirect(para.returnUrl);
        }
    });
});






module.exports = router;